package com.buvaka;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;

import java.io.FileOutputStream;
import java.io.IOException;

import com.buvaka.features.Features;


public class UpdateGeoJsonFile {
    static final String VAR_GEOJSON = "var featureCollections = ";

    public static void update (MongoClient client) {

        try (FileOutputStream fout = new FileOutputStream( "src/main/webapp/js/gis.js")){

            MongoClient mongo = client;
            DB db = mongo.getDB("gis");
            DBCollection points = db.getCollection("points");
            DBCursor allPoints = points.find();
            FileChannel fc2 = fout.getChannel();

            StringBuilder str = new StringBuilder(VAR_GEOJSON).append(Features.OPEN).append(Features.TYPE_FEATURE_COLLECTION).append(Features.COMMA).append(Features.FEATURES).append(Features.OPEN_ARRAY);
            while (allPoints.hasNext()) {
                str.append(allPoints.next().toString()).append(Features.COMMA);
            }

            DBCollection links = db.getCollection("links");
            DBCursor allLinks = links.find();
            while (allLinks.hasNext()) {
                str.append(allLinks.next().toString()).append(Features.COMMA);
            }

            str.setLength(str.length() - 2); //remove comma + space at the end
            str.append(Features.CLOSE_ARRAY).append(Features.CLOSE).append(";");
            fc2.write(ByteBuffer.wrap(str.toString().getBytes("UTF-8")));
            
            

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    

}
